import { useToastError, useToastSuccess } from "@/hooks/useToast";
import { Button } from "@mui/material";
import { log } from "console";
import React, { useState } from "react";
import ChoiceItem from "../ChoiceItem";
import "./choice.less";
interface IProp {
  data: IQuestionItem;
}

const typeMap: StringMap = {
  one: "单选",
  many: "多选",
  check: "判断",
};
// 选择题型的组件
export default function Choice({ data }: IProp) {
  const success = useToastSuccess();
  const error = useToastError();
  const [opts, setOpts] = useState<IQuestionTypeKeyMap[]>(
    JSON.parse(data.optionContent)
  );

  // 我们需要一个可以记录当前这道题，勾选了哪些答案 -- 需要一个数组所多个答案存起来
  const [answers, setAnswers] = useState<string[]>([]);

  const changeAnswer = (value: string) => {
    if (data.questionType === "many") {
      // 如果是多选，
      if (answers.includes(value)) {
        // 1. 如果有答案，我们要的操作是取消选择，要从数组里面删除
        const idx = answers.findIndex((item) => item === value);
        answers.splice(idx, 1);
      } else {
        // 1. 如果答案数组里面没有对应的答案，把答案添加到数组里面
        answers.push(value);
      }
      setAnswers([...answers]);
    } else {
      // 如果是单选，就直接让数组里面只有一个答案
      setAnswers([value]);
    }
  };

  const checkAnswer = () => {
    // 判断用户选择的数组里面的答案，是否和参考答案一致
    // 但是在把数组转换为字符串之前，要做一次排序，因为用户选择的顺序可能是乱的
    // 但是后端返回的答案是按 a b c 的顺序的
    const userAnswer = answers.sort().join(",");
    if (userAnswer === data.answer) {
      success("回答正确");
    } else {
      error("回答错误");
    }
  };
  return (
    <div className="choice">
      <section className="detail">
        <span className="type">{typeMap[data.questionType]}</span>
        <div className="title">{data.title}</div>
      </section>
      <section>
        {opts.map((item) => (
          <ChoiceItem
            key={item.key}
            data={item}
            onChange={changeAnswer}
            answers={answers}
          />
        ))}
      </section>
      <section className="answer-area">
        <Button variant="outlined" onClick={checkAnswer}>
          确定
        </Button>
        <section className="answer">
          <div>参考答案：</div>
          <div>{data.answer}</div>
        </section>
      </section>
    </div>
  );
}
